<?php


namespace app\controller\admin;


use app\common\exception\ApiException;
use app\model\partner\UserPartnerModel;
use app\model\user\PartnerWithdrawRecordModel;
use app\model\user\UserModel;
use app\model\user\UserWithdrawModel;
use app\service\user\PartnerMoneyRecordService;
use app\service\user\UserMoneyDetailService;
use app\service\utils\WeiXinPayService;
use think\facade\Db;

class PartnerWithdrawController extends BaseAdminController
{

    function setModel()
    {
        return new PartnerWithdrawRecordModel();
    }

    function setWithModel()
    {
        return ['user'];
    }

    function setSearch()
    {
        return [
            '=' => ['user.mobile' => 'mobile', 'status', 'type'],
            'betweenTimestamp' => ['create_time']
        ];
    }

    function setSort()
    {
        // TODO: Implement setSort() method.
    }

    public function audit()
    {
        Db::startTrans();
        try {
            $id = $this->request->param('id');
            $status = $this->request->param('status'); //0待转账 1已打款 2打款失败
            $reason = $this->request->param('reason', '', 'trim');
            if ($status == 2 && !$reason) {
                throw new ApiException("请备注打款失败原因");
            }
            $info = PartnerWithdrawRecordModel::find($id);
            if (!$info) {
                throw new ApiException("提现记录不存在");
            }
            if ($info['status'] != 0) {
                throw new ApiException("提现已审核");
            }
            $info->status = $status;
            $info->remark = $reason;
            $info->audit_time = time();
            $info->save();
            $userId = $info['user_id'];
            $money = $info['money'];
            $orderSn = $info['order_sn'];
            $openId = UserPartnerModel::where('id', $userId)->value('openid');
            if ($status == 1) {
                $weiXinPayService = new WeiXinPayService(1);
                $weiXinPayService->toBalance($orderSn, $openId, intval($money * 100), '陪驾教练提现');
            } else {
                if ($info['type'] == 2) {
                    $detailMoneyService = new PartnerMoneyRecordService();
                    $type = PartnerMoneyRecordService::WITHDRAW_BACK;
                    $title = $detailMoneyService->getTypeText($type);
                    $detailMoneyService->createLog($title, $userId, $type, $money, 0, $orderSn);
                }
            }
            Db::commit();
            return $this->success();
        } catch (\Exception $exception) {
            Db::rollback();
            return $this->error($exception);
        }
    }
}